<?php
/**
 * 命令行具体执行程序
 * 1)必须放置于cli/script目录下
 * 2)文件名必须为小写的cli_xxxx.php
 * 3)类名必须为Cli_Xxxx格式
 * 4)必须包含一个run($args)方法,$args为自动转换后的命令行参数
 *
 * 调用方法:
 * <code>
 * cli script=demo username=sharmy
 * </code>
 *
 * 命令行应用示例
 *
 */
// Cli_socket::run();
class Cli_socket {
	public function run($args) {
	      set_time_limit ( 0 );
	      //写功能
	      // $tip = "php cli.php script=socket acctid = acctid";
	      // if(!isset($args['acctid']))
	      // {
	      //     exit($tip);
	      // }
	      //获取socketport
	        $socketport = acct::find(array("id"=>1))->getOne();
	      
		    if (!(class_exists('swoole_websocket_server')))
		    {
		        return $this->error('Swoole扩展未安装或服务未启动');
		    }
		    //配置进程数心跳检测间隔时间SSL
	        $config = array('worker_num' => 1, 'daemonize' => 1,'heartbeat_check_interval' => 30);
	        $this->server = new swoole_websocket_server("127.0.0.1", $socketport->socket,SWOOLE_BASE);

	        $this->server->set($config);
	        $this->server->on('open', function (swoole_websocket_server $server, $request) {
	            echo "server: handshake success with fd{$request->fd}\n";
	        });
	        //$this->server->heartbeat();
	        $this->server->on('message', function (swoole_websocket_server $server, $frame) {
	            echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}".'\n';
	            $host = __FILE__;
	            $data = json_decode($frame->data,true);
	            if(!empty($data['msg_type']) && $data['msg_type']=="heart"){
            		$this->server->push($frame->fd, 'tong');
            	}
	            if(empty($data['acct_id']) || (empty($data['user_id']) && empty($data['openid']))|| empty($data['video_id']) ){
	            	
	            	echo json_encode("not data".'\n');
	            }
	            else{
	            	$redis = new Helper_redis();
	            	$message=$this->msg($data);
		            //查询刚添加的数据，推送给用户
		            if(!empty($data['openid']) && $message['code']==1){
		            	//初始化连接
		            	$user_obj = acctuser::find(array("wechat_open_id"=>$data['openid']))->getOne();
		            	//加入连接池
				        $rv = $redis->get("edulive:$host:socket_pool:live:".$data['video_id']);
				        $pconnects = $redis->get("edulive:$host:socket_pool:connects:".$frame->fd);
				        if(empty($pconnects) || $pconnects!=$data['video_id']){
				        	$redis->set("edulive:$host:socket_pool:connects:".$frame->fd,json_encode(array("video_id"=>$data['video_id'],"openid"=>$data['openid'])));
				        }

				        //更新连接池
						//   echo '这是连接池1'.var_dump($rv);
				        if(!empty($rv)){
				        	$fd_arr = json_decode($rv,true);
				        	if(!in_array($frame->fd, $fd_arr)){
				        		array_push($fd_arr, $frame->fd);
				        		$redis->set("edulive:$host:socket_pool:live:".$data['video_id'],json_encode($fd_arr));
				        	}
				        }else{
				        	$fd_arr = array($frame->fd);
				        	$redis->set("edulive:$host:socket_pool:live:".$data['video_id'],json_encode($fd_arr));
				        }
				        // $room = $this->getRoomUser($fd_arr,$redis,$host);
				        if($user_obj->id()){
				        	$join_user = array(
				        		"id"=>$user_obj->id,
				        		"nickname"=>!empty($user_obj->username)?$user_obj->username:$user_obj->nickname,
				        		"avatar_url"=>$user_obj->avatar_url,
				        	    'type'=>'join',
				        	);
				        }
				        
				        $pushmsg = array(
				        	"video_id"=>$data['video_id'],
				        	"join_user"=>$join_user?$join_user:array(),
				        	"live_user"=>video::getLiveRoomUserNumber($data['video_id'],$host,$redis),
				        	// "list"=>$room,
				         
				        );
				        echo "当前服务器共有 ".count($this->server->connections). " 个连接\n";
				     
		                //推送消息
		                // var_dump($this->server->connections);
		                //加入直播间消息
		                foreach ( $fd_arr as $fd) {
		                   //echo "当前连接 ".var_dump($fd);
		                	// if(in_array($fd, $fd_arr) ){
		                	    if(!empty($pushmsg) ){
		                	        @$this->server->push($fd, json_encode($pushmsg,JSON_UNESCAPED_UNICODE));
		                	        echo("PUSH");
		                	    }
		                		
		                	// }
		                }
		            }
		            if($message['code']==0){
		            	
				        $rv = $redis->get("edulive:$host:socket_pool:live:".$data['video_id']);
				        $connects = $redis->get("edulive:$host:socket_pool:connects:".$frame->fd);
				        if(empty($connects) || $connects!=$data['video_id']){
				        	$redis->set("edulive:$host:socket_pool:connects:".$frame->fd,$data['video_id']);
				        }
				        if(!empty($rv)){
				        	$fd_arr = json_decode($rv,true);
				        	if(!in_array($frame->fd, $fd_arr)){
				        		array_push($fd_arr, $frame->fd);
				        		$redis->set("edulive:$host:socket_pool:live:".$data['video_id'],json_encode($fd_arr));
				        	}
				        }else{
				        	$fd_arr = array($frame->fd);
				        	$redis->set("edulive:$host:socket_pool:live:".$data['video_id'],json_encode($fd_arr));
				        }
		                //推送消息
		                foreach ($fd_arr as $fd) {
		                	// echo json_encode($fd.'\n');
		                	// if(in_array($fd, $fd_arr)){
		                		@$this->server->push($fd, json_encode($message['data'],JSON_UNESCAPED_UNICODE));
		                	// }
		                    
		                }
		            }

		            if($message['code']==2){
		            	@$this->server->push($frame->fd, json_encode($message,JSON_UNESCAPED_UNICODE));
		            }
	            }
	            

	        });
	        $this->server->on('Start', function()
	        {
	            swoole_set_process_name('EDULIVE');
	        });
	        $this->server->on('close', function ($ser, $fd) {
	        	$host = __FILE__;
	        	$redis = new Helper_redis();

		        $connects = $redis->get("edulive:$host:socket_pool:connects:".$fd);
		        if(!empty($connects)){
		        	$rv = $redis->get("edulive:$host:socket_pool:live:".$connects);
		        	$arr=array();
		        	if(!empty($rv)){
		        		$arr = json_decode($rv,true);
		        		$arr = array_merge(array_diff($arr, array($fd)));
		        	}
		        	$redis->set("edulive:$host:socket_pool:live:".$connects,json_encode($arr));
		        	$redis->del("edulive:$host:socket_pool:connects:".$fd);
		        }
	            echo "client {$fd} closed".'\n';

	        });

	        $this->server->start();
	      
	}

	//保存消息到数据库
	public function msg($data){
		if(empty($data['content']) && empty($data['upload_img'])){
			echo("no_msg ".'\n');
			return [
	                'code'=>1,
	                'msg'=>'没有数据',
	            ];
		}

		try {
			//dump($data);
			$user_info = acctuser::find(array("wechat_open_id"=>$data['user_id']))->asArray()->getOne();

			$user_id = $user_info['id'];
			if(empty($user_id)){
				echo("no_user ".'\n');
				return [
	                'code'=>2,
	                'msg'=>'未取得用户信息',
	            ];
			}
			$acct = acct::find('id=1')->getOne();
			if($acct->id()){
				if(empty($data['upload_img'])){
					$safe_res = Helper_Common::wxsafeMsg($acct->app_id,$acct->app_secret,$data['content'],'msg');
				}
				else{
					$safe_res = Helper_Common::wxsafeMsg($acct->app_id,$acct->app_secret,$data['upload_img'],'pic');
				}
				if(!empty($safe_res['errcode']) && $safe_res['errcode']==87014){
					return [
		                'code'=>2,
		                'msg'=>'发送失败，内容包含敏感信息！',
		            ];
				}
				// var_dump($safe_res);
			}
			$save_data=array(
    		"video_id"=> empty($data['video_id'])?"":$data['video_id'],
    		"user_id"=>$user_id,
    		"acct_id"=>empty($data['acct_id'])?"":$data['acct_id'],
    		"content"=>empty($data['content'])?"":trim($data['content']),
    		"upload_img"=>empty($data['upload_img'])?"":json_encode([$data['upload_img']])
	    	);
			
	    	$comment = new comment($save_data);
	    	
	    	$comment->save();
	    	$id = $comment->id;


	        

	        if(!empty($user_info)){
	        	$data['nickname']=empty($user_info['nickname'])?"":$user_info['nickname'];
	        	$data['avatar_url']=empty($user_info['avatar_url'])?"":$user_info['avatar_url'];
	        	$data['content']=$this->userTextDecode(trim($data['content']));
	        	$data['upload_img'] = empty($data['upload_img'])?"":[$data['upload_img']];
	        	$data['id']=$id;
	            return [
	                'code'=>0,
	                'msg'=>'success',
	                'data'=>$data
	            ];
	        }else{
	        	echo("no_user_info ".'\n');
	            return [
	                'code'=>2,
	                'msg'=>'未取得用户信息',
	            ];
	        }
		} catch (Exception $e) {
			echo("error ".'\n');
			dump($e);
			 return [
	                'code'=>2,
	                'msg'=>'错误',
	            ];
		}
		
	}

	public  function userTextDecode($str){
        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback('/\\\\\\\\/i',function($str){
            return '\\';
        },$text); //将两条斜杠变成一条，其他不动
        return json_decode($text);
    }

}